package main

import (
	"bufio"
	"context"
	"fmt"
	"github.com/wailsapp/wails/v2/pkg/runtime"
	"net"
)

// 客户端
type Client struct {
	Ip     string
	Online bool
	Conn   net.Conn
	ctx    context.Context
}

// 创建客户端
func NewClient(ctx context.Context, ip string, conn net.Conn) *Client {
	client := &Client{
		Ip:     ip,
		Online: true,
		Conn:   conn,
		ctx:    ctx,
	}
	go client.Read()
	return client
}

// 客户端读取数据
func (c *Client) Read() {
	defer c.Conn.Close()
	for {
		reader := bufio.NewReader(c.Conn)
		var buf [128]byte
		n, err := reader.Read(buf[:]) // 读取数据
		if err != nil {
			fmt.Println("read from client failed, err:", err)
			c.Online = false
			runtime.EventsEmit(c.ctx, "clientsUpdate", c)
			break
		}
		recvStr := string(buf[:n])
		runtime.EventsEmit(c.ctx, "message", recvStr)
		fmt.Println("收到client端发来的数据：", recvStr)
	}
}

// 向客户端写入数据
func (c *Client) Write(data []byte) error {
	_, err := c.Conn.Write(data)
	if err != nil {
		return err
	}
	return nil
}
